/*
 * CAudioRender.cpp
 *
 *  Created on: 2016年3月18日
 *      Author: terry
 */

#include "CAudioRender.h"

#include "MediaProp.h"
#include "TStringCast.h"
#include "MediaConst.h"

#include "CAudioDevice.h"


namespace av
{

CAudioRender::CAudioRender():
		m_device(),
		m_state()
{

	m_device.reset(new CAudioDevice());
}

CAudioRender::~CAudioRender()
{
	close();
}

bool CAudioRender::getTimePoint(int64_t& clock, int64_t& pts)
{
	if (!m_device)
	{
		return false;
	}

	pts = m_device->getCurTime(&clock);
	return true;
}

void CAudioRender::close()
{
	m_device->close();
}

bool CAudioRender::isOpen()
{
	return m_device->isOpen();
}

int CAudioRender::play()
{
	m_device->pause(false);
	setState(STATE_PLAYING);

	return 0;
}

int CAudioRender::pause()
{
	m_device->pause(true);

	setState(STATE_PAUSED);

	return 0;
}

void CAudioRender::stop()
{
	pause();

	setState(STATE_STOPPED);

	m_device->setScale(av_make_q(1,1));
}


int CAudioRender::getState()
{
	return m_state;
}

void CAudioRender::setFormat(const MediaFormat& fmt)
{

}

int CAudioRender::write(AVFramePtr frame)
{
	m_device->write(frame.get());

	return 0;
}

void CAudioRender::flush()
{
	m_device->flush();
}


void CAudioRender::setScale(AVRational scale)
{
	m_device->setScale(scale);
}

bool CAudioRender::setProp(const std::string& name, const std::string& value)
{
	if (name == MEDIA_PLAYER_PROP_LIVE_MODE)
	{
		bool liveMode = false;
		comn::StringCast::toValue(value, liveMode);
		m_device->setLiveMode(liveMode);
	}
    else if (name == MEDIA_PLAYER_PROP_MAX_DURATION)
    {
        int duration = MAX_CACHE_DURATION;
        comn::StringCast::toValue(value, duration);
        m_device->setMaxDuration(duration);
    }

    return true;
}

/**
 * 打开音频播放设备
 * @param sampleRate    采样率,取值有：8000,16000,32000
 * @param channels      通道数， 取值[1,2]
 * @param sampleFmt     采样格式
 * @return
 */
int CAudioRender::open(int sampleRate, int channels, int sampleFmt)
{
	if (!m_device->open(channels, sampleRate, sampleFmt))
	{
		return ENODEV;
	}

	return 0;
}


/**
 * 获取音量
 * @return
 */
float CAudioRender::getVolume()
{
	return m_device->getVolume();
}

/**
 * 设置音量
 * @param vol   取值范围：[0.0,1.0]
 * @return
 */
int CAudioRender::setVolume(float vol)
{
	return m_device->setVolume(vol);
}

bool CAudioRender::isMute()
{
	return m_device->isMute();
}

int CAudioRender::setMute(bool muted)
{
	return m_device->setMute(muted);
}

void CAudioRender::dropTo(int64_t pts)
{
	m_device->dropTo(pts);
}

void CAudioRender::setState(StreamState state)
{
	comn::AutoCritSec lock(m_cs);
	m_state = state;
}



} /* namespace av */
